package chances.system.operator.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import chances.system.log.entity.ActionLog;
import chances.system.operator.entity.Oplog;
import chances.system.operator.entity.Role;
import chances.system.operator.repo.RoleRepository;


@RestController
public class RoleController {

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	 
	@Autowired
	RoleRepository roleRepository;
	
	@Autowired
	PermissionController permissionController;
	
	@ActionLog(operateType=Oplog.OP_EDIT, objName="role", desc="修改角色'{name}'")
	@RequestMapping(path = "/sys/role/save", method = RequestMethod.POST)
	public Role saveRole(HttpServletRequest request, @RequestBody RoleModel model) {
		Role role = this.roleRepository.save(model.getRole());
		model.setObjId(role.getId());
		if(StringUtils.isNotBlank(model.getObjType())){
			permissionController.savePermission(request, model);
		}
		
		request.setAttribute("role", role);
		return role;
	}

	@ActionLog(operateType=Oplog.OP_EDIT, objName="role", desc="修改角色'{name}'状态")
	@RequestMapping(path = "/sys/role/status", method = RequestMethod.POST)
	public Role updateStatus(HttpServletRequest request, @RequestBody RoleModel model) {
		Role role = this.roleRepository.findOne(model.getId());
		role.setStatus(model.getStatus());
		role = this.roleRepository.save(role);
		request.setAttribute("role", role);
		return role;
	}
}